package com.lvcoding.jwtdemo.filter;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lvcoding.jwtdemo.util.JwtUtil;
import com.lvcoding.jwtdemo.util.Res;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String token = request.getHeader("token");

        if (request.getRequestURI().contains("login")) {
            filterChain.doFilter(request, response);
            return;
        }

        if (StrUtil.isBlank(token)) {
            response.setContentType("application/json;charset=utf-8");
            String result = objectMapper.writeValueAsString(Res.fail(401, "token不能为空", null));
            response.getWriter().write(result);
            return;
        }

        DecodedJWT decodedJWT = JwtUtil.parseToken(token);
        if (decodedJWT == null) {
            response.setContentType("application/json;charset=utf-8");
            String result = objectMapper.writeValueAsString(Res.fail(401, "登录超时", null));
            response.getWriter().write(result);
            return;
        }

        String username = decodedJWT.getClaim("username").asString();
        String age = decodedJWT.getClaim("age").asString();

        request.setAttribute("username", username);
        request.setAttribute("age", age);

        filterChain.doFilter(request, response);
    }
}
